<template>
  <div class="trigger">
    <ReturnPage class="mb10" />
    <!-- 操作按钮 -->
    <el-button
      type="primary"
      class="ml10"
      size="mini"
      @click="dialogVisible = true"
      >新增</el-button
    >
    <el-button
      type="primary"
      class="ml10"
      size="mini"
      :disabled="!multipleSelection.length"
      @click="changeStatus(0)"
      >启用</el-button
    >
    <el-button
      type="info"
      class="ml10"
      size="mini"
      :disabled="!multipleSelection.length"
      @click="changeStatus(1)"
      >禁用</el-button
    >
    <el-button
      type="danger"
      class="ml10"
      size="mini"
      :disabled="!multipleSelection.length"
      @click="delTrigger"
      >删除</el-button
    >
    <!-- 列表数据 -->
    <div class="tp_box mt10">
      <el-table
        :data="tableData"
        height="calc(100vh - 260px)"
        @selection-change="handleSelectionChange"
        size="mini"
        >>
        <el-table-column type="selection" width="50"> </el-table-column>
        <el-table-column
          prop="priority"
          label="严重性"
          align="center"
          width="80"
        >
          <template slot-scope="scope">
            <el-tag :type="scope.row.priority < 3 ? 'warning' : 'danger'">{{
              scope.row.priority | getPriority
            }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="value" label="值" align="center" width="60">
          <template slot-scope="scope">
            <el-tag :type="scope.row.value == 0 ? 'success' : 'warning'">{{
              scope.row.value | getValue
            }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column
          prop="description"
          label="名称"
          align="left"
          width="200"
        >
        </el-table-column>
        <el-table-column
          width="200"
          prop="opdata"
          label="Operational data"
          align="left"
        >
        </el-table-column>
        <el-table-column prop="expression" label="表达式" align="left">
        </el-table-column>
        <el-table-column prop="status" label="状态" align="center" width="70">
          <template slot-scope="scope">
            <el-tag :type="scope.row.status == '0' ? 'success' : 'danger'">{{
              scope.row.status == "0" ? "已启用" : "已禁用"
            }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="error" label="信息" align="center" width="50">
          <template slot-scope="scope">
            <el-tooltip
              v-if="scope.row.error"
              :content="scope.row.error"
              placement="bottom"
              effect="light"
            >
              <i
                class="el-icon-warning"
                style="color: #f56c6c; transform: scale(1.5); cursor: pointer"
              ></i>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <pagination
        v-show="total > 0"
        :total="total"
        :page.sync="pageNum"
        :limit.sync="pageSize"
        @pagination="getTableData()"
      />
    </div>

    <!-- 新增弹窗 -->
    <el-dialog
      title="新增"
      :visible.sync="dialogVisible"
      width="40%"
      @close="closeDialog('form')"
    >
      <div class="form_box">
        <el-form
          :rules="rules"
          label-width="140px"
          ref="form"
          :model="form"
          size="mini"
        >
          <el-form-item label="名称" prop="description">
            <el-input
              v-model="form.description"
              placeholder="请输入触发器名称"
              style="width: 200px"
            ></el-input>
          </el-form-item>
          <el-form-item label="事件名称" prop="event_name">
            <el-input
              v-model="form.event_name"
              placeholder="请输入事件名称"
              style="width: 200px"
            ></el-input>
          </el-form-item>
          <el-form-item label="Operational data" prop="opdata">
            <el-input
              v-model="form.opdata"
              placeholder="请输入Operational data"
              style="width: 200px"
            ></el-input>
          </el-form-item>
          <el-form-item label="严重性" prop="priority">
            <el-radio-group v-model="form.priority">
              <el-radio-button label="0">未分类</el-radio-button>
              <el-radio-button label="1">信息</el-radio-button>
              <el-radio-button label="2">警告</el-radio-button>
              <el-radio-button label="3">一般严重</el-radio-button>
              <el-radio-button label="4">严重</el-radio-button>
              <el-radio-button label="5">灾难</el-radio-button>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="表达式" prop="expression">
            <div class="expressions_box">
              <el-input
                type="textarea"
                autosize
                v-model="form.expression"
                placeholder="请输入表达式"
              ></el-input>
              <el-button
                size="mini"
                class="ml10"
                @click="dialogVisible_expression = !dialogVisible_expression"
                >添 加</el-button
              >
            </div>
            <!-- <span style="font-size: 12px; cursor: pointer; color: #409eff"
              >表达式构造器</span
            > -->
          </el-form-item>
          <el-form-item label="允许手动关闭" prop="manual_close">
            <el-checkbox v-model="form.manual_close"></el-checkbox>
          </el-form-item>
          <el-form-item label="描述" prop="comments">
            <el-input
              type="textarea"
              rows="4"
              v-model="form.comments"
            ></el-input>
          </el-form-item>
          <el-form-item label="已启用" prop="status">
            <el-checkbox v-model="form.status"></el-checkbox>
          </el-form-item>
        </el-form>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm('form')" size="mini"
          >添 加</el-button
        >
        <el-button @click="dialogVisible = false" size="mini">取 消</el-button>
      </span>
    </el-dialog>

    <!-- 添加表达式弹窗 -->
    <el-dialog
      title="条件"
      :visible.sync="dialogVisible_expression"
      width="40%"
      :before-close="handleClose"
    >
      <el-form
        :rules="rules"
        label-width="80px"
        ref="form_expression"
        :model="form_expression"
        size="mini"
      >
        <el-form-item label="监控项" prop="monitor">
          <el-input
            v-model="form_expression.monitor"
            style="width: 300px"
            disabled
          ></el-input>
          <el-button
            @click="dialogVisible_monitor = !dialogVisible_monitor"
            class="ml10"
            >选择</el-button
          >
        </el-form-item>
        <el-form-item label="结果" prop="result">
          <el-select
            v-model="form_expression.result"
            placeholder="请选择"
            style="width: 100px"
          >
            <el-option label="=" value="1"></el-option>
            <el-option label="<>" value="2"></el-option>
            <el-option label=">" value="3"></el-option>
            <el-option label="<" value="4"></el-option>
            <el-option label=">=" value="5"></el-option>
            <el-option label="<=" value="6"></el-option>
          </el-select>
          <el-input
            v-model="form_expression.num"
            style="width: 100px"
            class="ml10"
          ></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="addCondition('form_expression')"
          >插 入</el-button
        >
        <el-button @click="dialogVisible_expression = false">取 消</el-button>
      </span>
    </el-dialog>

    <!-- 选择监控项的弹窗 -->
    <el-dialog
      title="监控项"
      :visible.sync="dialogVisible_monitor"
      width="50%"
      :before-close="handleClose"
    >
      <el-table
        :data="monitor_tableData"
        size="mini"
        height="calc(100vh - 300px)"
        @row-click="chooseMonitor"
        :cell-style="cellStyle"
      >
        <el-table-column
          prop="name"
          label="名称"
          align="center"
          show-overflow-tooltip
        >
        </el-table-column>
        <el-table-column
          prop="key_"
          label="键值"
          align="center"
          show-overflow-tooltip
        >
        </el-table-column>
        <el-table-column
          prop="type"
          label="类型"
          align="center"
          show-overflow-tooltip
        >
          <template slot-scope="scope">{{ scope.row.type | getType }}</template>
        </el-table-column>
        <el-table-column
          prop="type"
          label="信息类型"
          align="center"
          show-overflow-tooltip
        >
          <template slot-scope="scope">{{
            scope.row.value_type | getValueType
          }}</template>
        </el-table-column>
        <el-table-column
          prop="status"
          label="状态"
          align="center"
          show-overflow-tooltip
        >
          <template slot-scope="scope"
            ><el-tag
              size="mini"
              :type="scope.row.status ? 'danger' : 'success'"
              >{{ scope.row.status ? "禁用" : "启用" }}</el-tag
            ></template
          >
        </el-table-column>
      </el-table>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible_monitor = false">取 消</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import {
  getTrigger_Api, //触发器查询
  addTrigger_Api, //触发器添加
  updateTrigger_Api, //触发器编辑
  delTrigger_Api, //触发器删除
  getMonitor_Api, //监控项查询
} from "@/api/automated/host.js";
import Template from "../ConfigurationManagement/model/Template.vue";
export default {
  components: { Template },
  data() {
    return {
      //列表数据
      tableData: [],
      //监控项列表数据
      monitor_tableData: [],
      //分页
      query: {
        output: "extend",
        hostids: null,
        selectTags: "extend",
        // triggerids: ["17578"],
      },
      //多选
      multipleSelection: [],
      //触发器表单
      form: {
        description: null, //名称
        event_name: null, //事件名称
        opdata: null, //Operational_data
        priority: 0, //严重性
        expression: null, //表达式
        manual_close: null, //允许手动关闭
        comments: null, //描述
        status: null, //启用
      },
      //添加表达式表单
      form_expression: {
        monitor: null, //监控项
        result: "1", //结果选择
        num: 0, //结果输入
        key_: null, //选中的键值
      },
      //验证规则
      rules: {
        //名称
        description: [
          { required: true, message: "请输入名称", trigger: "blur" },
        ],
        //表达式
        expression: [
          { required: true, message: "请输入表达式", trigger: "blur" },
        ],
        //添加表达式的监控项
        monitor: [{ required: true, message: "请选择监控项", trigger: "blur" }],
        num: [{ required: true, message: "请输入数字", trigger: "blur" }],
      },
      ip: null, //自动化页面过来的id
      name: null, //自动化页面来的主机名
      //控制新增表单弹窗显示隐藏
      dialogVisible: false,
      //控制表达式添加弹窗
      dialogVisible_expression: false,
      //控制表达式添加选择监控项的弹窗
      dialogVisible_monitor: false,
      //分页
      pageSize: 10,
      pageNum: 1,
      total: 0,
      allData: [], //所有数据
    };
  },
  methods: {
    //获取触发器数据
    getList() {
      getTrigger_Api(this.query).then((res) => {
        this.allData = res.data;
        this.total = res.data.length;
        this.getTableData();
      });
    },
    //分页获取数据
    getTableData() {
      this.tableData = this.allData.slice(
        (this.pageNum - 1) * this.pageSize,
        this.pageNum * this.pageSize
      );
    },
    //获取监控项列表数据
    getMonitorList() {
      getMonitor_Api({
        output: "extend",
        hostids: this.$route.query.hostid,
      }).then((res) => {
        this.monitor_tableData = res.data;
      });
    },
    //多选
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    //关闭弹窗
    closeDialog(formName) {
      this.$refs[formName].resetFields();
    },
    //提交
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          //允许手动关闭
          this.form.manual_close
            ? (this.form.manual_close = 1)
            : (this.form.manual_close = 0);
          //状态
          this.form.status ? (this.form.status = 0) : (this.form.status = 1);
          addTrigger_Api(this.form).then((res) => {
            this.$message.success(res.msg);
            this.dialogVisible = false;
            this.getList();
          });
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    //修改监控项状态
    changeStatus(state) {
      //获取id数组
      const itemIds = this.multipleSelection.map((item) => item.triggerid);
      const tempArr = itemIds.map((item) => {
        return updateTrigger_Api({ status: state, triggerid: item });
      });
      //获取结果
      Promise.all(tempArr).then((res) => {
        this.$message.success("操作成功");
        this.getList();
      });
    },
    //删除监控项
    delTrigger() {
      const itemIds = this.multipleSelection.map((item) => item.triggerid);
      delTrigger_Api(itemIds.join(",")).then((res) => {
        this.$message.success(res.msg);
        this.getList();
      });
    },
    //选择一个监控项
    chooseMonitor(row) {
      this.form_expression.monitor = this.ip + ":" + row.name;
      this.form_expression.key_ = row.key_;
      this.dialogVisible_monitor = false;
    },
    //设置监控项列表样式
    cellStyle({ row, column, columnIndex }) {
      if (columnIndex === 0) {
        return "color:#409eff;cursor:pointer";
      } else {
        return "";
      }
    },
    //插入条件
    addCondition(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.form.expression =
            "last(/" + this.name + "/" + this.form_expression.key_ + ")=0";
          this.dialogVisible_expression = false;
        } else {
          return false;
        }
      });
    },
  },
  created() {
    //获取主机id
    this.query.hostids = this.$route.query.hostid;
    //获取ip地址
    this.ip = this.$route.query.ip;
    this.name = this.$route.query.name;
    // this.form.expression = `last(/${this.name}/icmpping)=0`;
    //获取触发器数据
    this.getList();
    //获取监控项列表数据
    this.getMonitorList();
  },
  filters: {
    //过滤严重性
    getPriority(val) {
      switch (val) {
        case 0:
          return "未分类";
        case 1:
          return "信息";
        case 2:
          return "警告";
        case 3:
          return "一般严重";
        case 4:
          return "严重";
        case 5:
          return "灾难";
      }
    },
    //过滤值
    getValue(val) {
      switch (val) {
        case 0:
          return "正常";
        case 1:
          return "问题";
      }
    },
    //过滤类型
    getType(val) {
      switch (val) {
        case 0:
          return "Zabbix 客户端";
        case 2:
          return "zabbix 采集器";
        case 3:
          return "简单检查";
        case 5:
          return "内部检查";
        case 7:
          return "zabbix agent（主动）";
        case 9:
          return "web监控项";
        case 10:
          return "外部检查";
        case 11:
          return "数据库监控";
        case 12:
          return "IPMI agent";
        case 13:
          return "SSH agent";
        case 14:
          return "Telnet agent";
        case 15:
          return "可计算的监控";
        case 16:
          return "JMX agent";
        case 17:
          return "SNMP trap";
        case 18:
          return "相关项监控";
        case 19:
          return "HTTP agent";
        case 20:
          return "SNMP agent";
        case 21:
          return "脚本";
      }
    },
    //过滤监控项信息类型
    getValueType(val) {
      switch (val) {
        case 0:
          return "浮点型";
        case 1:
          return "字符";
        case 2:
          return "日志";
        case 3:
          return "无符号数字";
        case 4:
          return "文本";
      }
    },
  },
};
</script>

<style lang="scss" scoped>
//表达式样式（表单）
.expressions_box {
  display: flex;
  justify-content: flex-start;
  align-items: flex-start;
}
</style>